import { CCBoolean, CCInteger, Component, _decorator } from "cc";
import { Agent } from "./Agent";
import { Academy } from "./Academy";


const { ccclass, executionOrder, menu, property } = _decorator;

@ccclass('DecisionRequester')
@executionOrder(10)
@menu('ML Agents/Decision Requester')
export class DecisionRequester extends Component {

    @property({ range: [1, 20] })
    decisionPeriod: number = 5;

    @property({ displayName: "Repeat Action" })
    takeActionsBetweenDecisions: boolean = true;

    private _agent: Agent = null!;

    get agent(): Agent {
        return this._agent;
    }

    onLoad() {
        this._agent = this.node.getComponent(Agent)!;
        Academy.instance.agentPreStep = this.makeRequests.bind(this);
    }

    onDestroy() {
        if (Academy.isInitialized) {
            Academy.instance.agentPreStep = () => { };
        }
    }

    makeRequests(academyStepCount: number) {
        const context = {
            academyStepCount: academyStepCount
        };
        if (this.shouldRequestDecision(context)) {
            this._agent?.requestDecision();
        }

        if (this.shouldRequestAction(context)) {
            this._agent?.requestAction();
        }
    }

    protected shouldRequestDecision(context: { academyStepCount: number }): boolean {
        return context.academyStepCount % this.decisionPeriod === 0;
    }

    protected shouldRequestAction(context: { academyStepCount: number }): boolean {
        return this.takeActionsBetweenDecisions;
    }
}
